<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>

<body>
  <script>
    // 1. 数组去重
    let arr = [11, '11', '11', NaN, NaN, 23, 22, 11, 22, 11, 23, { name: 'zs' }, { name: 'zs' }, { name: 'li' }, [1, 2], [1, 2, 3], [1, 2, 3]]

    // Set数据结构
    function handleArr(arr) {
      return [...new Set(arr)]
    }
    let arr1 = handleArr(arr)
    console.log('set数据结构去重：', arr1);

    // 利用对象属性唯一性
    function handleArr1(arr) {
      let newArr = []
      let obj = {}
      for (let i = 0; i < arr.length; i++) {
        // console.log(typeof arr[i] + arr[i]);
        if (!obj[typeof arr[i] + arr[i]]) {
          obj[typeof arr[i] + arr[i]] = 1
          newArr.push(arr[i])
        }
      }
      return newArr
    }
    let arr2 = handleArr1(arr)
    console.log(arr2);

    let arrObj = [
      { name: 'zs' },
      { name: 'zs' },
      { name: 'zs' },
      { name: 'ls' }
    ]
    // 2. 数组对象去重——reduce遍历+对象属性唯一性
    function handleArr2(arr) {
      let newObj = {}
      return arr.reduce((pre, cur) => {
        // newObj[cur.name] ? '' : newObj[cur.name] = pre.push(cur)
        if (!newObj[cur.name]) {
          newObj[cur.name] = 1
          pre.push(cur)
        }
        return pre
      }, [])
    }
    let arr3 = handleArr2(arrObj)
    console.log(arr3);

    // for循环
    function distinct1(arr, key) {
      var newobj = {}, newArr = [];
      for (var i = 0; i < arr.length; i++) {
        var item = arr[i];
        if (!newobj[item[key]]) {
          newobj[item[key]] = newArr.push(item);
        }
      }
      return newArr;
    }

    // 快排
    let arr4 = [1, 55, 23, 44, 20]
    function qSort(arr) {
      // 当只剩一项时结束递归
      if (arr.length <= 1) {
        return arr
      }
      // 找到数组中间项，取出此项（改变原数组）
      let midIndex = Math.floor(arr.length / 2)
      let midVal = arr.splice(midIndex, 1)
      // 定义两个数组，左数组放小于中间项值，右数组放大于中间项值
      let left = [],
        right = []
      // 循环遍历数组比较每项与中间的值
      for (let i = 0; i < arr.length; i++) {
        arr[i] < midVal ? left.push(arr[i]) : right.push(arr[i])
      }

      // 递归调用，拼接左侧数组+中间项+右侧数组
      return qSort(left).concat(midVal, qSort(right))
    }
    console.log(qSort(arr4));
  </script>

</body>

</html>